package com.indusfo.spc.controller;

import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.MaterialXOService;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: IEIS2-COM
 * @Package: com.indusfo.spc.controller
 * @ClassName: MaterialXOController
 * @Author: 熊冰
 * @Description: 物料视图层
 * @Date: 2019/8/19 10:44
 * @Version: 1.0
 */

@Controller
@RequestMapping("/materialXO")
public class MaterialXOController {
    @Resource
    MaterialXOService materialXOService;

    @Resource
    UploadMapper uploadMapper;
    //新增
    @RequestMapping(value="insertMaterialXO")
    @ResponseBody
    public JSONObject insertMaterialXO(MaterialXO materialXO){
        materialXO.setlMatId(null);
        JSONObject json = materialXOService.insertOrUpdateMaterialXO(materialXO) ;
        return json;

    }

    //删除
    @RequestMapping(value="delMaterialXO")
    @ResponseBody
    public JSONObject delMaterialXO(Long[] ids){
        Integer   dataState = 2;
        JSONObject json = materialXOService.deleteMaterialXO(ids,dataState);
        return json;

    }
    //更新
    @RequestMapping(value="updateMaterialXO")
    @ResponseBody
    public JSONObject updateMaterialXO(MaterialXO materialXO){
        JSONObject json = materialXOService.insertOrUpdateMaterialXO(materialXO) ;
        return json;

    }
    //全查
    @RequestMapping(value="queryMaterialXO")
    @ResponseBody
    public JSONObject queryMaterialXO(MaterialXO materialXO){

        //根据标识来判断是进行高级查询还是全查
        JSONObject  json = materialXOService.listMaterialXO(materialXO);
        return json;
    }

    //停用
    @RequestMapping(value="stopMaterialXO")
    @ResponseBody
    public JSONObject stopMaterialXO(Long[] ids){
        Integer   dataState = 3;
        JSONObject json = materialXOService.deleteMaterialXO(ids,dataState);
        return json;

    }
    //启用
    @RequestMapping(value="startMaterialXO")
    @ResponseBody
    public JSONObject startMaterialXO(Long[] ids){
        Integer   dataState = 1;
        JSONObject json = materialXOService.deleteMaterialXO(ids,dataState);
        return json;

    }

    /**
     * @author: louk
     * @Description: 高级查询接口
     * @date: 2019/10/14 20:21
     *
     */
    @RequestMapping(value = "/advancedQuery")
    @ResponseBody
    public JSONObject advancedQuery(MaterialXO materialXO){
        JSONObject json = materialXOService.advancedQuery(materialXO);
        return json;
    }
    /**
     * @author: louk
     * @Description: 物料Excel导入
     * @date: 2019/11/5 16:12
     *
     */
    @RequestMapping("/uploadFileMaterial")
    @ResponseBody
    public JSONObject uploadFileUser(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        //定义一个message对象用于向前台传输数据
        Message msg = new Message();
        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        if (wb == null) {
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                msg.setCode(2);
                msg.setMsg("未找到需要导入的表格");
                errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
            } else {
                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    msg.setCode(1);
                    msg.setMsg("未找到需要导入的数据，请确认表格是否保存！！！");
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认表格是否保存！！！"));
                } else {
                    List<MaterialXO> addProductPlans = new ArrayList<>();
                    for (int i = 1; i <= rowCount; i++) {
                        boolean needAdd = true;
                        //获取到每一行的每一列的数据
                        //物料编号
                        String vcMatCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
                        //物料名称
                        String vcProjectName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
                        //规格型号
                        String vcModel =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 2, false);
                        //物料类别
                        String mtype = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 3, false);
                        //单位
                        String matunit = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 4, false);
                        //来源
                        String lSourceName =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 5, false);
                        //条码规则
                        String rule =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 6, false);
                        //版本号
                        String versionNumber =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 7, false);
                        //图号
                        String figureNumber = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 8, false);
                        //客户代码
                        String customerCode =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 9, false);
                        //单位数量
                        String lMatUnitCountContent =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 10, false);
                        Integer lMatUnitCount=null;
                        if(StringUtils.isBlank(lMatUnitCountContent)){
                            if(StringUtils.isNumeric(lMatUnitCountContent)){
                                lMatUnitCount=Integer.valueOf(lMatUnitCountContent);
                            }

                        }
                        //成品机型
                        String finishedProductModeltCount = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 11, false);
                        //资源数
                        String resourceContent= com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 12, false);
                        Integer resourceNumber=null;
                        if(StringUtils.isBlank(resourceContent)){
                            if(StringUtils.isNumeric(resourceContent)){
                                resourceNumber=Integer.valueOf(lMatUnitCountContent);
                            }

                        }

                        //生产节拍
                        String productionTaktContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 13, false);
                        Integer productionTakt=null;;
                        if(StringUtils.isBlank(productionTaktContent)){
                            if(StringUtils.isNumeric(productionTaktContent)){
                                productionTakt=Integer.valueOf(resourceContent);
                            }
                        }
                        //干燥时间
                        String dryingTimeContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 14, false);
                        Integer dryingTime=null;
                        if(StringUtils.isBlank(dryingTimeContent)){
                            if(StringUtils.isNumeric(productionTaktContent)){
                                productionTakt = Integer.valueOf(resourceContent);
                            }
                        }
                        //保有量
                        String inventoryContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 15, false);
                        Integer inventory=null;
                        if(StringUtils.isBlank(inventoryContent)){
                            if(StringUtils.isNumeric(inventoryContent)){
                                inventory=Integer.valueOf(inventoryContent);
                            }
                        }
                        //报工数量
                        String workNumberContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 16, false);
                        Integer workNumber=null;
                        if(StringUtils.isBlank(workNumberContent)){
                            if(StringUtils.isNumeric(workNumberContent)){
                                workNumber=Integer.valueOf(workNumberContent);
                            }
                        }
                        MaterialXO plan=new MaterialXO(vcMatCode,vcProjectName,vcModel,mtype,matunit,lSourceName,rule,versionNumber,figureNumber,customerCode,lMatUnitCount,finishedProductModeltCount,resourceNumber,productionTakt,dryingTime,inventory,workNumber);
                        int m = i + 1;
                        //将excel中的每一行数据存储进行检查
                        String result = materialXOService.checkExcelContent(plan);
                        if(result!=null){
                            errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
                            needAdd=false;
                        }
                        for (int j = 1; j < i; j++) {
                            //判断物料编码  物料名称是否重复
                            String oldvcMatCode =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 0, false);
                            String oldvcProjectName =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 1, false);
                            if (StringUtils.isBlank(vcMatCode) && oldvcMatCode.equals(vcMatCode)) {
                                needAdd = false;
                                errorDatas.add( ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同物料编码"));
                            }
                            if ( StringUtils.isBlank(vcProjectName) && oldvcProjectName.equals(vcProjectName)) {
                                needAdd = false;
                                errorDatas.add( ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同物料名称"));
                            }
                        }
                        if (needAdd) {
                            addProductPlans.add(plan);
                        } else {
                            msg.setCode(2);
                            msg.setMsg("导入数据中存在异常信息");
                        }

                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (msg.getCode() == 2 && !way) {
                        msg.setMsg(msg.getMsg() + ",中止导入");
                    } else {
                        if (addProductPlans.size() > 0) {
                            try {
                                uploadMapper.updateListMaterial(addProductPlans);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                msg.setMsg(StringUtils.isBlank(msg.getMsg()) ? "导入成功" : msg.getMsg());
                                if ("导入成功".equals(msg.getMsg())) {
                                    msg.setCode(1);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                msg.setMsg("导入失败");
                            }
                        }
                    }
                    //msg.setData(GsonUtil.toJson(errorDatas));
                }
            }
        }
        msg.setData(GsonUtil.toJson(errorDatas));
        //response.getWriter().println(GsonUtil.toJson(msg));
        String s = GsonUtil.toJson(msg);
        return JSONObject.build(200,msg.getMsg(),errorDatas);
    }

}
